import csv
import openpyxl
from openpyxl import load_workbook
import logging
import getpath
import os
import myglobal
import config_json
import sample
def getdata_raw(fname):
    xl_book = openpyxl.load_workbook(filename=fname)
    table = xl_book.worksheets[0]
    data = []
    for row in table.values:
        r = []
        for one in row:
            if one is not None:
                r.append(one)
            else:
                r.append(None)
        data.append(r)
    return data #None# dataframe1
def zl_data(data):
    r=[]
    record_begin=False
    for i in range(len(data)):
        row=data[i]
        if row[0]=="元素校正浓度":#new record begin
            if record_begin:
                record={"items":items,"eles":eles}#sometime eles not all exists
                r.append(record)
            record_begin=True
            items=[]
            eles=None
            continue
        # print(row[0],type(row[0]))
        # if row[0]=="":#file end
        #     print("file end")
        #     if record_begin:
        #         print("has last record")
        #         record_begin=False
        #         record={"items":items,"eles":eles}
        #         r.append(record)
        #     else:
        #         print("no")
        #     break
        if row[0]=="-":
            continue
        if row[0]=="样品名：":
            eles=row[3:]
            continue
        # print(row[2],type(row[2]))
        if row[2].isnumeric():
            print("is ele")
            items.append({"id":row[0],"conc":row[3:]})
            continue
    #last one
    record={"items":items,"eles":eles}
    r.append(record)
    return r
def getdata(fname):
    data0=getdata_raw(fname)
    data=zl_data(data0)
    return data
def getDataObjects(fname):
    data=getdata(fname)
    num=0
    r=[]
    for one in data:
        for item in one["items"]:
            s=sample.Sample()
            s.sampleid=item["id"]
            _items=[(ele,"") for ele in one["eles"]]
            concs=item["conc"]
            s.num=num
            j=0
            for item in _items:
                if item[0]!=None:
                    s.items[item]=concs[j]
                    j+=1
            r.append(s)
            num+=1
    return r    
def test_getdata():
    fname=os.path.join(getpath.getpath(),"..","hlp","斯派克光谱_点数据.xlsx")#"6300.xls")
    data=getDataObjects(fname)
    return data
if __name__=="__main__":
    data=test_getdata()
    print(data)
